package com.designpattern.ProxyPattern;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author yp
 * @Date 2021-05-25
 * @Description 动态代理-->CGLIB代理
 **/

public class ProxyExampleCGLIB {
    public static void main(String[] args) {

        BuyHouse buyHouse = new BuyHouseImpl();
        CglibProxy cglibProxy = new CglibProxy();

        BuyHouseImpl buyHouseCglibProxy = (BuyHouseImpl) cglibProxy.getInstance(buyHouse);
        buyHouseCglibProxy.buyHosue();
    }
}


class CglibProxy implements  MethodInterceptor {

    private Object object;

    public Object getInstance(final Object object){
        this.object = object;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.object.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理操作：买房前准备");
                 Object result = methodProxy.invoke(object, args);
                 System.out.println("代理操作：买房后装修");
                 return result;
    }
}